import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Response } from './common/response'
import { BusinessExceptionFilter } from './common/filters/business-exception.filter'
import { ValidationPipe } from '@nestjs/common';
import { NestExpressApplication } from '@nestjs/platform-express';
import * as session from 'express-session'
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { join } from 'path';
import { IoAdapter } from '@nestjs/platform-socket.io';
import { ErrorCode } from './common/errorcode';
import { BusinessException } from './common/exceptions/business.exception';
import { Req } from '@nestjs/common';
function middleWareAll(req: { session: any; path: string | string[]; }, res: any, next: () => void) {
  // console.log('middleWareAll', req.session);
  if (req.path.includes('/login')) {
    next()
    return
  }
  // if (req.session.USER_LOGIN_STATE == null) {
  //   throw new BusinessException('未登录', ErrorCode.NOT_LOGIN);
  // }
  next()
}

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  // 配置WebSocket适配器
  app.useWebSocketAdapter(new IoAdapter(app));

  app.enableCors({
    origin: ['http://songkaiguo.cn', 'http://localhost:5173', 'http://127.0.0.1:5500','http://111.229.148.175'], // 替换为实际的客户端域名
    credentials: true, // 允许携带凭证
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    allowedHeaders: 'Content-Type, Accept, Authorization',
  });
   app.use(session({ secret: "SKG", name: "kgg.session", rolling: true, cookie: { maxAge: 1000 * 60*60 } }))
  app.useGlobalInterceptors(new Response())
  app.useGlobalFilters(new BusinessExceptionFilter())
  app.useGlobalPipes(new ValidationPipe());
  app.use(middleWareAll)

  const options = new DocumentBuilder().setTitle('博客接口文档').setDescription('博客接口文档').setVersion('1').build()
  const document = SwaggerModule.createDocument(app, options)
  SwaggerModule.setup('/api-docs', app, document)
  /* 配置静态资源目录,不然上传的图片无法访问 */
  console.log(join(process.cwd(), 'public'));

  app.useStaticAssets(join(process.cwd(), 'src/public'), {
    prefix: '/public'
  })
  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
